<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告信息区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="category_options">
        <el-col>
          <span>请选择商品分类：</span>
          <!-- 商品分类级联框 -->
          <el-cascader
            clearable
            filterable
            v-model="selectedKeys"
            :options="categories"
            :props="categoryProps"
            @change="updateParams"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 参数tabs标签区域 -->
      <el-tabs v-model="activeName" @tab-click="updateParams">
        <!-- 动态参数分页面板 -->
        <el-tab-pane :label="'动态' + titleText" name="dynamic">
          <el-button
            type="primary"
            size="small"
            :disabled="isAddParamDisabled"
            @click="showAddParamDialog"
          >添加{{titleText}}</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="dynamicParams" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 动态参数值组 -->
                <el-tag
                  class="el-tag-new"
                  v-for="(val, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteVal(scope.row,index)"
                >{{val}}</el-tag>
                <!-- 添加动态参数值的输入框 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  class="el-input-tag-new"
                  size="small"
                  ref="newValRef"
                  v-model="scope.row.inputValue"
                  @blur="addNewVal(scope.row)"
                ></el-input>
                <!-- 显示动态参数值输入框的按钮 -->
                <el-button
                  v-else
                  class="el-button-tag-new"
                  size="small"
                  icon="el-icon-circle-plus"
                  @click="showValEditInput(scope.row)"
                >新标签</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column :label="titleText + '名称'" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="showDeleteParamConfirm(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数分页面板 -->
        <el-tab-pane :label="'静态' + titleText" name="static">
          <el-button
            type="primary"
            size="small"
            :disabled="isAddParamDisabled"
            @click="showAddParamDialog"
          >添加{{titleText}}</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="staticParams" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 静态属性值 -->
                <el-tag
                  class="el-tag-new"
                  v-for="(val, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteVal(scope.row,index)"
                >{{val}}</el-tag>
                <!-- 添加静态属性值的输入框 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  class="el-input-tag-new"
                  size="small"
                  ref="newValRef"
                  v-model="scope.row.inputValue"
                  @blur="addNewVal(scope.row)"
                ></el-input>
                <!-- 显示静态属性值输入框的按钮 -->
                <el-button
                  v-else
                  class="el-button-tag-new"
                  size="small"
                  icon="el-icon-circle-plus"
                  @click="showValEditInput(scope.row)"
                >新标签</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column :label="titleText + '名称'" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditParamDialog(scope.row)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="showDeleteParamConfirm(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数/属性弹出框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamDialogVisible"
      width="30%"
      @close="addParamDialogClosed"
    >
      <!-- 添加表单 -->
      <el-form :model="addParamForm" ref="addParamRef" :rules="paramRules" label-width="80px">
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParam">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数/属性弹出框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editParamDialogVisible"
      width="30%"
      @close="editParamDialogClosed"
    >
      <!-- 编辑表单 -->
      <el-form :model="editParamForm" ref="editParamRef" :rules="paramRules" label-width="80px">
        <el-form-item :label="titleText + '名称'" prop="attr_name">
          <el-input v-model="editParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editParamDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParam">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categories: [],
      // 商品分类选择相关
      selectedKeys: [1, 4, 23],
      categoryProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      // tabs标签相关
      activeName: "dynamic",
      dynamicParams: [],
      staticParams: [],
      // 添加参数弹出框相关
      addParamDialogVisible: false,
      addParamForm: {
        attr_name: ""
      },
      paramRules: {
        attr_name: [
          {
            required: true,
            message: `请输入名称`,
            trigger: "blur"
          }
        ]
      },
      // 编辑参数弹出框相关
      editParamDialogVisible: false,
      editParamForm: {},
      // 动态参数值添加相关
      isValEditting: false,
      edittingVal: ""
    };
  },
  methods: {
    async getCategories() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      this.categories = res.data;
    },
    async updateParams() {
      if (this.isAddParamDisabled) {
        this.selectedKeys = [];
        this.dynamicParams = [];
        this.staticParams = [];
        return;
      }
      const { data: res } = await this.$http.get(
        `categories/${this.selectedCategoryId}/attributes`,
        {
          params: { sel: this.activeName === "dynamic" ? "many" : "only" }
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类参数失败");
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      if (this.activeName === "dynamic") {
        this.dynamicParams = res.data;
      } else {
        this.staticParams = res.data;
      }
    },
    // 删除参数/属性确认框
    async showDeleteParamConfirm(attr) {
      const result = await this.$confirm(
        `此操作将永久删除此${this.titleText}且不可恢复，是否确认`,
        "提示",
        {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }
      );
      if (result !== "confirm") {
        return this.$message.error("操作已取消");
      }
      this.deleteParamById(attr.attr_id);
    },
    async deleteParamById(id) {
      const { data: res } = await this.$http.delete(
        `categories/${this.selectedCategoryId}/attributes/${id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error(`删除分类${this.titleText}失败`);
      }
      this.$message.success(`删除分类${this.titleText}成功)`);
      this.updateParams();
    },
    // 添加参数/属性弹出框
    showAddParamDialog() {
      this.addParamDialogVisible = true;
    },
    addParamDialogClosed() {
      this.addParamForm.attr_name = "";
    },
    addParam() {
      this.$refs.addParamRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.selectedCategoryId}/attributes`,
          {
            attr_name: this.addParamForm.attr_name,
            attr_sel: this.activeName === "dynamic" ? "many" : "only",
            attr_vals: "a,b,c"
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error(`添加分类${this.titleText}失败`);
        }
        this.addParamDialogVisible = false;
        this.$message.success(`添加分类${this.titleText}成功`);
        this.updateParams();
      });
    },
    // 编辑参数/属性确认框
    showEditParamDialog(attr) {
      this.editParamForm = attr;
      this.editParamDialogVisible = true;
    },
    editParamDialogClosed() {
      this.editParamForm = {};
    },
    editParam() {
      this.$refs.editParamRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.selectedCategoryId}/attributes/${this.editParamForm.attr_id}`,
          {
            attr_name: this.editParamForm.attr_name,
            attr_sel: this.activeName === "dynamic" ? "many" : "only"
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error(`修改分类${this.titleText}失败`);
        }
        this.editParamDialogVisible = false;
        this.$message.success(`修改分类${this.titleText}成功`);
        this.updateParams();
      });
    },
    // 添加新动态属性
    showValEditInput(attr) {
      attr.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.newValRef.$refs.input.focus();
      });
    },
    addNewVal(attr) {
      if (attr.inputValue.trim().length > 0) {
        attr.attr_vals.push(attr.inputValue.trim());
        this.saveVals(attr);
      }
      attr.inputVisible = false;
      attr.inputValue = "";
    },
    deleteVal(attr, index) {
      attr.attr_vals.splice(index, 1);
      this.saveVals(attr);
    },
    async saveVals(attr) {
      const { data: res } = await this.$http.put(
        `categories/${this.selectedCategoryId}/attributes/${attr.attr_id}`,
        {
          attr_name: attr.attr_name,
          attr_sel: attr.attr_sel,
          attr_vals: attr.attr_vals.join(" ")
        }
      );

      if (res.meta.status !== 200) {
        return this.$message.error(`更新分类${this.titleText}的值失败`);
      }
      this.$message.success(`更新分类${this.titleText}的值成功`);
    }
  },
  computed: {
    isAddParamDisabled() {
      return this.selectedKeys.length < 3;
    },
    selectedCategoryId() {
      return this.isAddParamDisabled
        ? ""
        : this.selectedKeys[this.selectedKeys.length - 1];
    },
    titleText() {
      return this.activeName === "dynamic" ? "参数" : "属性";
    }
  },
  created() {
    this.getCategories();
    this.updateParams();
  }
};
</script>

<style lang="less" scoped>
.category_options {
  margin: 15px 0;
}

.el-tag-new {
  margin: 10px;
}

.el-input-tag-new {
  width: 120px;
}
</style>
